package com.dhecp.project.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.core.utils.dingtalk.DingTalkUtils;
import com.dhecp.core.utils.dingtalk.DtApiUrls;
import com.dhecp.core.utils.qywx.QyWxHttpUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName DingTalkController
 * @Description TODO
 * @Author alula
 * @Date 2022-03-07 14:13
 */
@Controller
@RequestMapping("/dingtalk")
public class DingTalkController {

    /**  获取最新钉钉凭证，过期则更新
     * @return systemSetting
     */
    @RequestMapping("/getTicket")
    @ResponseBody
    public AjaxResult getTicket() {
        String ticket =  DingTalkUtils.getTicket(DingTalkUtils.getToken(DingTalkUtils.H5APPKEY, DingTalkUtils.H5APPSECERT, DingTalkUtils.H5CACHEKEY));
        String corpId = DingTalkUtils.getCorpId();
        String agentId= DingTalkUtils.getAgentId();
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("corpId", corpId);
        dataMap.put("agentId", agentId);
        dataMap.put("ticket", ticket);
        return AjaxResult.success(dataMap);
    }

    /**  手动更新企业微信凭证
     * @return systemSetting
     */
    @RequestMapping("/updateTicket")
    @ResponseBody
    public AjaxResult updateTicket() {
        String ticket =  DingTalkUtils.updateTicket(DingTalkUtils.getToken(DingTalkUtils.H5APPKEY, DingTalkUtils.H5APPSECERT, DingTalkUtils.H5CACHEKEY));
        return AjaxResult.success(ticket);
    }

    /**  获取访问用户身份
     * @return AjaxResult
     */
    @RequestMapping("/getUserInfo")
    @ResponseBody
    public AjaxResult queryUserInfo(@RequestParam Map<String, Object> params) {
        String token = DingTalkUtils.getToken(DingTalkUtils.H5APPKEY, DingTalkUtils.H5APPSECERT, DingTalkUtils.H5CACHEKEY);
        String requestUrl = DtApiUrls.USERINFO_GET_URL.replace("ACCESS_TOKEN", token).replace("CODE", params.get("code").toString());//填充凭证
        JSONObject jsonObject = QyWxHttpUtils.sendGet(requestUrl);//发起请求
        return AjaxResult.success(jsonObject);
    }
}
